package com.ruanjian.reggie.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruanjian.reggie.common.CustomException;
import com.ruanjian.reggie.dto.SetmealDto;
import com.ruanjian.reggie.entity.Setmeal;
import com.ruanjian.reggie.entity.SetmealDish;
import com.ruanjian.reggie.mapper.SetmealMapper;
import com.ruanjian.reggie.service.SetmealDishService;
import com.ruanjian.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServcieImp extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    public void saveSetmealAndDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        Long setmealDtoId = setmealDto.getId();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDtoId);
            return setmealDishes;

        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    public void editSetmealDish(SetmealDto setmealDto) {
        this.updateById(setmealDto);
        setmealDishService.remove(new LambdaQueryWrapper<SetmealDish>().eq(SetmealDish::getSetmealId,setmealDto.getId()));
        setmealDto.getSetmealDishes().stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDto.getSetmealDishes());

    }

    @Override
    @Transactional
    public void removeWithDish(String ids) {
        List<String> collect = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId,collect);
        wrapper.eq(Setmeal::getStatus,1);
        int count = this.count(wrapper);
        if (count > 0){
            throw new CustomException("套餐还在出售，不能删除");
        }
        this.removeByIds(collect);
        setmealDishService.remove(new LambdaQueryWrapper<SetmealDish>().in(SetmealDish::getSetmealId,collect));

    }


}
